import store from '@/store'
import { login, UserResult } from '@/api/login'
import { setToken, getToken } from '@/utils/auth'
export const useUserStore = defineStore('user', {
  state: () => ({
    // 用户名
    username: null,
    // 页面级别权限
    roles: null,
    // user info
    userInfo: null,
  }),
  getters: {},
  actions: {
    /** 存储用户名 */
    SET_USERNAME(username: string) {
      this.username = username
    },
    /** 存储角色 */
    SET_ROLES(roles: Array<string>) {
      this.roles = roles
    },
    /**
     * @description 登录
     * @param {*} data
     */
    async login(data) {
      return new Promise<UserResult>((resolve, reject) => {
        login(data)
          .then((res) => {
            if (res.code === 200) {
              setToken(res.data)
              resolve(res)
            }
          })
          .catch((error) => {
            reject(error)
          })
      })
    },
    /**
     * @description 重置token、roles、permission、router等
     */
    async resetAll() {
      this.setToken('')
    },
    /** 刷新`token` */
    async handRefreshToken(data) {},
  },
})

export function useUserStoreHook() {
  return useUserStore(store)
}
